import { mapState } from 'vuex'
import { permissionController } from '@/utils/index'

export default {
  data() {
    return {
      size: 'mini',
      localValue: null,
    }
  },
  props: {
    value: {
      type: [String, Array, Date, Number],
    },
    tableField: {
      type: Object,
    },
    tableStatus: {
      type: Object,
    },
    birthmark: {
      type: String,
    },
    embeddedTable: {
      type: Array,
    },
    tableFieldList: {
      type: Array,
    },
  },
  computed: {
    ...mapState({
      table: state => state.treatment.table,
    }),
    disabled: function () {
      if (this.birthmark) {
        const [variable, index] = this.birthmark.split('--')
        if (this.embeddedTable && this.embeddedTable.length > index) {
          const { tableFieldList } = this.embeddedTable[index]
          const target = tableFieldList.filter(tableField => tableField.variable === variable)[0]
          return target && target.controlled
        }
      } else {
        return this.tableField.controlled
      }
      return false
    },
    readOnly: function () {
      return (
        !this.permissionController('subject::ecrf::data::entery') ||
        this.tableField.readOnly === '0' ||
        (this.tableStatus &&
          (this.tableStatus.isLapse === '2' || this.tableStatus.isLapse === '3' || this.tableStatus.frozen === '2'))
      )
    },
  },
  watch: {
    value: {
      handler: function (val) {
        this.localValue = val
      },
      deep: true,
      immediate: true,
    },
    localValue: {
      handler: function (val) {
        this.$emit('input', val)
      },
      deep: true,
    },
    disabled: {
      handler: function (val) {
        if (val) {
          if (this.tableField.variableType === '20') {
            this.$emit('input', [])
          } else {
            this.$emit('input', '')
          }
        }
      },
    },
  },
  methods: {
    permissionController,
  },
}
